<template>
  <div class="create-exam">
    <el-card>
      <template #header>
        <div class="card-header">
          <h3>创建考试</h3>
        </div>
      </template>

      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="100px"
        class="exam-form"
      >
        <!-- 基本信息 -->
        <el-form-item label="考试名称" prop="examName">
          <el-input v-model="formData.examName" placeholder="请输入考试名称" />
        </el-form-item>

        <el-form-item label="选择试卷" prop="paperId">
          <el-select
            v-model="formData.paperId"
            placeholder="请选择试卷"
            class="paper-select"
            @change="handlePaperChange"
          >
            <el-option
              v-for="paper in paperList"
              :key="paper.paperId"
              :label="paper.paperName"
              :value="paper.paperId"
            >
              <span>{{ paper.paperName }}</span>
              <span class="paper-info">
                ({{ paper.questionCount }}题 / {{ paper.totalScore }}分 /
                建议用时: {{ paper.duration }}分钟)
              </span>
            </el-option>
          </el-select>
          <el-button type="primary" @click="$router.push('/paper/add')">
            <el-icon> <Plus /> </el-icon>创建试卷
          </el-button>
        </el-form-item>

        <el-form-item label="考试时间" prop="timeRange">
          <el-date-picker
            v-model="formData.timeRange"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            :default-time="defaultTime"
            :disabled-date="disabledDate"
            :disabled-time="disabledTime"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>

        <el-form-item label="考试说明" prop="description">
          <el-input
            v-model="formData.description"
            type="textarea"
            :rows="3"
            placeholder="请输入考试说明"
          />
        </el-form-item>

        <!-- 是否公开 -->
        <el-form-item label="是否公开" prop="isPublic">
          <el-switch
            v-model="formData.isPublic"
            active-value="true"
            inactive-value="false"
          />
        </el-form-item>
        <!-- 提交按钮 -->
        <el-form-item>
          <el-button type="primary" @click="handleSubmit">创建考试</el-button>
          <el-button @click="$router.back()">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import { paperApi } from "../../api/paperApi";
import { examApi } from "../../api/examApi";
import { Plus } from "@element-plus/icons-vue";

const router = useRouter();
const formRef = ref(null);
const paperList = ref([]);

// 表单数据
const formData = reactive({
  examName: "",
  paperId: "",
  timeRange: [],
  description: "",
  isPublic: false, // 新增字段，默认不公开
});

// 默认时间
const defaultTime = [
  new Date(2000, 1, 1, 9, 0, 0),
  new Date(2000, 1, 1, 11, 0, 0),
];

// 表单验证规则
const rules = {
  paperName: [
    { required: true, message: "请输入考试名称", trigger: "blur" },
    { min: 2, max: 50, message: "长度在 2 到 50 个字符", trigger: "blur" },
  ],
  paperId: [{ required: true, message: "请选择试卷", trigger: "change" }],
  timeRange: [
    { required: true, message: "请选择考试时间", trigger: "change" },
    {
      validator: (rule, value, callback) => {
        if (value && value.length === 2) {
          const [start, end] = value;
          const duration = (new Date(end) - new Date(start)) / 1000 / 60;
          if (duration < 30) {
            callback(new Error("考试时长不能少于30分钟"));
          } else if (duration > 180) {
            callback(new Error("考试时长不能超过3小时"));
          } else {
            callback();
          }
        } else {
          callback();
        }
      },
      trigger: "change",
    },
  ],
};

// 获取试卷列表
const getPaperList = async () => {
  try {
    const res = await paperApi.getPaperPage({
      pageNumber: 1,
      pageSize: 100000,
    });
    paperList.value = res.result.data;
  } catch (error) {
    console.error("获取试卷列表失败:", error);
  }
};

// 试卷选择变化
const handlePaperChange = (paperId) => {
  const paper = paperList.value.find((p) => p.paperId === paperId);
  console.log(paper);
  if (paper) {
    formData.duration = paper.duration;
    formData.totalScore = paper.totalScore;
  }
};

// 禁用日期
const disabledDate = (time) => {
  return time.getTime() < Date.now() - 8.64e7; // 不能选择过去的日期
};

// 禁用时间
const disabledTime = (date) => {
  if (date) {
    const hours = date.getHours();
    return {
      disabledHours: () =>
        Array.from({ length: 24 }, (_, i) => i).filter((h) => h < 8 || h > 20),
    };
  }
  return {};
};

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return;

  try {
    await formRef.value.validate();

    const [startTime, endTime] = formData.timeRange;
    const examData = {
      examName: formData.examName,
      paperId: formData.paperId,
      startTime,
      endTime,
      description: formData.description,
      isPublic: formData.isPublic,
      totalScore: formData.totalScore,
      duration: formData.duration,
    };

    await examApi.createExam(examData);
    ElMessage.success("创建成功");
    router.push("/exam");
  } catch (error) {
    console.error("创建考试失败:", error);
  }
};

onMounted(() => {
  getPaperList();
});
</script>

<style scoped>
.create-exam {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.exam-form {
  max-width: 800px;
  margin: 0 auto;
}

.paper-select {
  width: 100%;
}

.paper-info {
  color: #909399;
  font-size: 13px;
  margin-left: 10px;
}
.paper-select {
  width: 85%;
}
</style>
